<?php
/**
 * Created by PhpStorm.
 * User: 程序猴
 * Date: 2018/4/9
 *  Q Q: 505413
 * Time: 10:36
 */

namespace app\admin\controller;
use app\admin\controller\Base;
use app\admin\model\UserType;
use app\admin\model\AuthRule as AuthRuleModel;
use think\Data;
use think\Db;
class Group extends Base
{
    //角色列表
    public function index()
    {
        $key = input('key');
        $map = [];
        if($key&&$key!=="")
        {
            $map['title'] = ['like',"%" . $key . "%"];
        }
        $user = new UserType();
        $lstObj = Db::name('auth_group')->where($map)->select();
        $this->assign('lstObj',$lstObj);
        return $this->fetch();
    }
    //添加角色
    public function groupAdd()
    {
        if(request()->isAjax()){
            $param = input('post.');
            if(!empty($param['rules'])){
                $param['rules'] = implode(',',$param['rules']);
            }
            if(!empty($param['status'])){
                if($param['status'] == 'on') {
                    $param['status'] = '1';
                }
            }else{
                $param['status'] = '0';
            }
            $param['create_time'] = time();
            $param['update_time'] = time();
            //dump($param);exit;
            $res = Db::name('auth_group')->insert($param);
            if($res){
                return json(['code' => 1, 'url' => 'reduction/index', 'msg' => '添加角色成功']);
            }else{
                return json(['code' => -1, 'url' => 'reduction/index', 'msg' => '添加角色失败，请重试']);
            }
        }
//        $authruleres = Db::name('auth_rule')->select();
//        $authruleres = Data::tree($authruleres,'title','id','pid');

        $authRule=new AuthRuleModel();
        $authRule=$authRule->authRuleTree();
        $this->assign('authrule',$authRule);
//        $this->assign('authruleres',$authruleres);

        return $this->fetch();
    }
    //编辑角色
    public function groupEdit()
    {
        $id = input('param.id');
        $group = new UserType();
        if(request()->isAjax()){
            $param = input('post.');
            if(!empty($param['rules'])){
                $param['rules'] = implode(',',$param['rules']);
            }
            if(!empty($param['status'])){
                if($param['status'] == 'on') {
                    $param['status'] = '1';
                }
            }else{
                $param['status'] = '0';
            }
            $param['update_time'] = time();
            $data = Db::name("auth_group")->where(array('id'=>$id))->update($param);
            if(false === $data){
                return json(['code' => -1, 'url' => 'group/index', 'msg' => '修改权限失败']);
            }else{
                return json(['code' => 1, 'url' => 'group/index', 'msg' => '修改权限成功']);
            }
        }
        $this->assign([
            'group' => $group->getOneRole($id)
        ]);
        $authRule=new AuthRuleModel();
        $authRule=$authRule->authRuleTree();
        $this->assign('authrule',$authRule);

        return $this->fetch();
    }
    //删除角色
    public function groupDel()
    {
        $id = input('id');
        $res = Db::name('auth_group')->where(array('id'=>$id))->delete();
        if($res){
            return json(['code' => 1, 'url' => 'reduction/index', 'msg' => '删除角色成功']);
        }else{
            return json(['code' => -1, 'url' => 'reduction/index', 'msg' => '删除角色失败，请重试']);
        }
    }
    //修改列表的开启状态
    public function status_edit()
    {
        $id = input('param.id');
        $status = Db::name('auth_group')->where('id',$id)->value('status');//判断当前状态情况
        if($status==1)
        {
            $flag = Db::name('auth_group')->where('id',$id)->setField(['status'=>0]);
            return json(['code' => 1, 'data' => $flag['data'], 'msg' => '已禁止']);
        }
        else
        {
            $flag = Db::name('auth_group')->where('id',$id)->setField(['status'=>1]);
            return json(['code' => 0, 'data' => $flag['data'], 'msg' => '已开启']);
        }

    }
    
    /**
     * 后台节点配置的url作为规则存入auth_rule
     * 执行新节点的插入,已有节点的更新,无效规则的删除三项任务
     */
    public function updateRules(){
        $menus = Db::name('menu')->field('id,pid,title,url,sort,status')->where(array('status' => array('EGT',0)))->order('sort asc')->select();
        $rules = Db::name('authRule')->order('name asc')->select();
        //构建insert数据
        $data     = array();//保存需要插入和更新的新节点
        foreach ($menus as $value){
            $temp['id']     =   $value['id'];
            $temp['pid']    =   $value['pid'];
            $temp['name']   =   $value['url'];
            $temp['title']  =   $value['title'];
            $temp['sort']   =   $value['sort'];
            $temp['module'] =   'admin';
            $temp['status'] =   $value['status'];
            if($value['pid'] > 0 ){
                $temp['type']   =   1;
            } else {
                $temp['type']   =   2;
            }
            $data[strtolower($temp['title'].$temp['name'].$temp['module'].$temp['type'])] = $temp;//去除重复项
        }
        $update = array();//保存需要更新的节点
        $ids    = array();//保存需要删除的节点的id
        foreach ($rules as $index=>$rule){
            $key = strtolower($rule['title'].$rule['name'].$rule['module'].$rule['type']);
            if ( isset($data[$key]) ) {//如果数据库中的规则与配置的节点匹配,说明是需要更新的节点
                $data[$key]['id'] = $rule['id'];//为需要更新的节点补充id值
                $update[] = $data[$key];
                unset($data[$key]);
                unset($rules[$index]);
                unset($rule['condition']);
                $diff[$rule['id']]=$rule;
            }elseif($rule['status'] >= 0){
                $ids[] = $rule['id'];
            }
        }
        
        if ( count($update) ) {
            foreach ($update as $k=>$row){
                if ( $row!=$diff[$row['id']] ) {
                    Db::name('authRule')->where(array('id'=>$row['id']))->setField($row);
                }
            }
        }
        if ( count($ids) ) {
            Db::name('authRule')->where( array( 'id'=>array('IN',implode(',',$ids)) ) )->setField(array('status'=>-1));
            //删除规则是否需要从每个用户组的访问授权表中移除该规则?
        }
        if( count($data) ){
            foreach ($data as $val){
                Db::name('authRule')->insert($val);
            }
        }
        return true;
       
    }
    function nodeTree($data, $pid = 0 ) {
        $return = array();
        foreach($data as $key => $val) {
            if($pid == $val['pid']){
                $child = $this->nodeTree($data, $val['id']);
                $val['child'] = $child ? $child : '';
                $return[] = $val;
            }
        }
        return $return;
    }
    //权限管理
    public function node(){
        $id = input('param.id');
        empty($id) && $this->error('参数错误');
        $roleinfo = Db::name('auth_group')->where(array('id' => $id))->field('id,title,rules')->find();
        $this->updateRules();
        $data   =   Db::name('authRule')->where(array('status' => '1'))->order('sort asc')->select();
        $rules = explode(',', $roleinfo['rules']);
        foreach ($data as $key => $val){
            if(in_array($val['id'], $rules)){
                $data[$key]['checked'] = 'checked';
            } else {
                $data[$key]['checked'] = '';
            }
        }
        $nodes  =   $this->nodeTree($data);
        $this->assign('nodes', $nodes);
        $this->assign('roleinfo', $roleinfo);
        return $this->fetch();
    }
    function updateRoleGroup(){
        $roleid =   input('param.roleid');
        $ids    =   trim(input('param.ids'),',');
        if(empty($roleid) || empty($ids)){
            return json(['code' => -1, 'msg' => '参数错误']);
        }
        $res = Db::name('auth_group')->where(array('id' => $roleid))->setField(array('rules' => $ids));
        if($res !== false){
            return json(['code' => 1, 'msg' => '更新成功']);
        } else {
            return json(['code' => -2, 'msg' => '更新失败']);
        }
    }


}